#include "headfile.h"
#define SUBMENU_TOTAL 4  // 二级菜单总项数（3设置项+返回）
#define OLED_WIDTH 128
#define OLED_HEIGHT 64
#define KEY_UP 1
#define KEY_DOWN 2
#define KEY_ENTER 3
static MenuItem current = MENU_VOICE; // 当前选中的一级菜单项
static SubMenuItem menu2_settings(void);//二级菜单系统设置声明
static SubMenuItem voice_control(void);//二级菜单语音控制声明
static MYItem menu2_my(void);//二级菜单我的声明
static MY_SET_ITEM Storage_SET(void);
uint8_t Voice_Start = 0;

// 全局定义DMA发送状态标志

/*#############################一级菜单#############################*/
/**
  * @简介     一级菜单绘制指定菜单项
  * @参数     item   - 要绘制的菜单项
  * @参数     offset - 横向偏移量（用于动画）
  */
void Draw(MenuItem item, int offset) {
    switch(item) {
        case MENU_VOICE:
            OLED_ShowImage(19+offset, 0, 90, 45, VoiceControl);
            OLED_ShowString(32+offset, 48, "语音控制", OLED_8X16);
            break;
        case MENU_MY:
            OLED_ShowImage(19+offset, 0, 90, 45, IsMy);
            OLED_ShowString(48+offset, 48, "我的", OLED_8X16);
            break;
        case MENU_SETTINGS:
            OLED_ShowImage(19+offset, 0, 90, 45, Setting);
            OLED_ShowString(32+offset, 48, "系统设置", OLED_8X16);
            break;
        default:
            OLED_Clear();
            OLED_ShowString(0, 0, "ERR:INVALID MENU", OLED_8X16);
            break;
    }
}

/**
  * @简介     一级菜单逻辑控制器
  * @返回值   用户最终选择的菜单项
  */
MenuItem menu1(void) {
    while(1) {
        int key = Key_GetNum();
        
        // 原有左右切换逻辑保持不变
        if(key == 1 || key == 2) { 
            int dir = (key == 1) ? -1 : 1;
            int new_idx = ((int)current - 1 + dir + MENU_COUNT) % MENU_COUNT;
            MenuItem newItem = (MenuItem)(new_idx + 1);
            Switch(current, newItem, dir);
            current = newItem;
        }
        // 确认键处理
        else if(key == 3) {
            OLED_Clear();
            if(current == MENU_SETTINGS)
							{
								//当menu2_settings调用时,意味着进入二级菜单的子状态
                if(menu2_settings() == SUBMENU_BACK) {
                    Draw(current, 0); // 返回后重绘一级菜单
										OLED_Clear();
                    OLED_Update();
                }
            }
						else if(current == MENU_MY)
							{
								if(menu2_my() == MYBACK)
									{
										Draw(current, 0); // 返回后重绘一级菜单
										OLED_Clear();
                    OLED_Update();
									}
            }
						else if(current ==	MENU_VOICE)
							{
                if(voice_control() == MYBACK)
									{
										Draw(current, 0); // 返回后重绘一级菜单
										OLED_Clear();
                    OLED_Update();
									}
            }
        }
        
        // 持续绘制当前菜单
        Draw(current, 0);
        OLED_Update();
    }
}

/*#############################1、二级菜单/语音控制#############################*/
/**
  * @简介     语音控制二级菜单
  * @返回值   用户选择的菜单项
  */
static SubMenuItem voice_control(void) {
    Voice_Start = 1;
    SubMenuItem currentSub = SUBMENU_BACK;
    uint8_t refresh = 1;
    uint32_t last_anim_time = 0;
    uint8_t current_frame = 0;

    while(1) {
        // 非阻塞动画更新（保持不变）
        if (HAL_GetTick() - last_anim_time >= 500) {
            refresh = 1;
            current_frame = (current_frame + 1) % 4;
            last_anim_time = HAL_GetTick();
        }

        // 绘制部分（保持不变）
        if (refresh) {
            OLED_Clear();
            OLED_ShowString(OLED_WIDTH/2-32, 0, "语音模式 ", OLED_8X16);
            switch(current_frame) {
                case 0: OLED_ShowImage(0, 18, 128, 64, ANIMATION0); break;
                case 1: OLED_ShowImage(0, 18, 128, 64, ANIMATION1); break;
                case 2: OLED_ShowImage(0, 18, 128, 64, ANIMATION2); break;
                case 3: OLED_ShowImage(0, 18, 128, 64, ANIMATION3); break;
            }
            OLED_Update();
            refresh = 0;
        }

        // 修改重点：处理十六进制UART数据
        if (uart_rx_flag) {
            
						int command;
            command = uart2_rx_buffer;
            
            switch(command) {  
                case 0:  // 十六进制表示
                    Play_MP3();
                    break;
                case 1:
                    Pause_MP3();
                    break;
                case 2:
                   Prev_MP3();
                    break;
                case 3:
									 Next_MP3();
                    break;
                case 4:
                    Volume_Add();
                    break;
                case 5:
                    Volume_Sub();
                    break;
								case 6:
										Mp3_LoopPlay();
                    break;
								case 7:
										Mp3_RandomPlay();
								case 8:
                    Mp3_RepeatPlay();
                    break;
                default:
                    // 可添加错误处理
                    break;
            }
            uart_rx_flag = 0;
            
            // 重新启动接收（持续监听）
            HAL_UART_Receive_IT(&huart2,&uart2_rx_buffer, 1); 
        }

        // 按键控制（保持不变）
        switch(Key_GetNum()) {
            case KEY_UP: break;
            case KEY_DOWN: break;
            case KEY_ENTER:
                if (currentSub == SUBMENU_BACK) {
                    Voice_Start = 0;
                    return SUBMENU_BACK;
                }
                break;
        }
        HAL_Delay(80);
    }
}

/*#############################二级菜单/系统设置#############################*/
/**
  * @简介     系统设置二级菜单
  * @返回值   用户选择的菜单项
  */
static SubMenuItem menu2_settings(void) {
		total_songs =Query_AllSongs();//发送查询指令
    SubMenuItem currentSub = SUBMENU_BACK;
    uint8_t refresh = 1;
    
    while(1) {
			//绘制部分
        if(refresh) {
            OLED_Clear();
            // 二级菜单布局
            OLED_ShowString(8, 0,  (currentSub == SUBMENU_BACK)    ? "<-"     : "  ",    OLED_8X16);
            OLED_ShowString(8, 16, (currentSub == SUBMENU_DISPLAY) ? "> 显示设置" : "  显示设置", OLED_8X16);
            OLED_ShowString(8, 32, (currentSub == Test_Mode)   ? "> 测试模式" : "  测试模式", OLED_8X16);
            OLED_ShowString(8, 48, (currentSub == SUBMENU_STORAGE) ? "> 存储设置" : "  存储设置", OLED_8X16);
            OLED_Update();
            refresh = 0;
        }
			//按键控制部分
        switch(Key_GetNum()) {
            case KEY_UP:
                currentSub = (currentSub == SUBMENU_BACK) ? SUBMENU_STORAGE : (SubMenuItem)(currentSub-1);
                refresh = 1;
                break;
                
            case KEY_DOWN:
                currentSub = (currentSub == SUBMENU_STORAGE) ? SUBMENU_BACK : (SubMenuItem)(currentSub+1);
                refresh = 1;
                break;
                
            case KEY_ENTER:
                if(currentSub == SUBMENU_BACK) {
                    return SUBMENU_BACK;
                } 
								else if(currentSub == SUBMENU_DISPLAY) {
                    // 传入具体回调函数//如果收到返回的值是枚举变量DISPLAY_SET_BACK的话，将refresh置为1，重绘当前菜单//
                    if(DisplaySettings(HandleBrightnessAdjust, HandleDisplayModeChange) == DISPLAY_SET_BACK) 
                    {
                        refresh = 1;
                    }
                }else if(currentSub == Test_Mode){
												if(Test_mode() == MYBACK){
												refresh = 1;
										}
								}else if(currentSub == SUBMENU_STORAGE){
												if(Storage_SET() == MYBACK){
												refresh = 1;
										}
								}
                break;
        }
        HAL_Delay(80);
    }
}

/*====================== 3.1三级菜单：系统设置>显示设置>亮度模式/显示模式 ======================*/
static DisplaySettingsItem DisplaySettings(BrightnessCallback brightnessHandler,DisplayModeCallback modeHandler) {
	
    DisplaySettingsItem currentItem = DISPLAY_SET_BACK; // 默认选中返回
    uint8_t refresh = 1;
    
    while(1) {
        if(refresh) {
            OLED_Clear();
            // 三级菜单布局
						OLED_ShowString(8, 0,(currentItem == DISPLAY_SET_BACK)      ? "<-" : " ", OLED_8X16);
            OLED_ShowString(8, 16,  (currentItem == DISPLAY_SET_BRIGHTNESS) ? "> 亮度等级" : "  亮度等级", OLED_8X16);
            OLED_ShowString(8, 32, (currentItem == DISPLAY_SET_MODE)       ? "> 显示模式" : "  显示模式", OLED_8X16);
            OLED_Update();
            refresh = 0;
        }

        switch(Key_GetNum()) {
            case KEY_UP:    // 上移
                currentItem = (currentItem == DISPLAY_SET_BACK) ? DISPLAY_SET_MODE : (DisplaySettingsItem)(currentItem - 1);
                refresh = 1;
                break;
                
            case KEY_DOWN:  // 下移
                currentItem = (currentItem == DISPLAY_SET_MODE) ? DISPLAY_SET_BACK : (DisplaySettingsItem)(currentItem + 1);
                refresh = 1;
                break;
                
            case KEY_ENTER: // 确认
                if(currentItem == DISPLAY_SET_BACK) {
                    return DISPLAY_SET_BACK;
                } else {
                    /* 通过回调执行实际功能 */
                    switch(currentItem) {
                        case DISPLAY_SET_BRIGHTNESS:
                            if(brightnessHandler) brightnessHandler();
                            break;
                        case DISPLAY_SET_MODE:
                            if(modeHandler) modeHandler();
                            break;
                        default: break;
                    }
                    refresh = 1; // 操作后刷新界面
                }
                break;
        }
        HAL_Delay(80);
    }
}

/*====================== 3.2 三级菜单：系统设置>测试模式>测试 ======================*/
static MY_SET_ITEM Test_mode(){
		MY_SET_ITEM currentItem = MYSET_BACK;
		uint8_t refresh = 1;
	
		while(1){
			uint8_t Volume = Query_Volume();;
			if(refresh) {
            OLED_Clear();
						OLED_ShowString(8, 0,(currentItem == MYSET_BACK)      ? "<-" : " ", OLED_8X16);
						OLED_ShowBinNum(16,16,Volume,10,OLED_6X8);
						OLED_ReverseArea(8,0,16,16);
            OLED_Update();
            refresh = 0;
        }
				switch(Key_GetNum()) {
            case KEY_UP:    // 上移
                break;
                
            case KEY_DOWN:  // 下移
                break;
                
            case KEY_ENTER: // 确认
                if(currentItem == MYSET_BACK) {
									return MYSET_BACK;//返回MYSET_BACK这个枚举值给上一级,上一级的函数判断后，将refresh置为1，重新刷新它那级的菜单s
                }
                break;
        }
        HAL_Delay(80);
		}
}

/*====================== 3.3 三级菜单：系统设置>存储设置>多少歌 ======================*/
static MY_SET_ITEM Storage_SET(){
		MY_SET_ITEM currentItem = MYSET_BACK;
		uint8_t refresh = 1;
	
		while(1){
			if(refresh) {
            OLED_Clear();
						OLED_ShowString(8, 0,(currentItem == MYSET_BACK)      ? "<-" : " ", OLED_8X16);
						char SongNuB[16];
						sprintf(SongNuB,"SongNumber:%d ",total_songs);
						OLED_ShowString(8, 16,SongNuB, OLED_8X16);
						OLED_ReverseArea(8,0,16,16);
            OLED_Update();
            refresh = 0;
        }
				switch(Key_GetNum()) {
            case KEY_UP:    // 上移
                break;
                
            case KEY_DOWN:  // 下移
                break;
                
            case KEY_ENTER: // 确认
                if(currentItem == MYSET_BACK) {
									return MYSET_BACK;//返回MYSET_BACK这个枚举值给上一级,上一级的函数判断后，将refresh置为1，重新刷新它那级的菜单s
                }
                break;
        }
        HAL_Delay(80);
		}
}

/*#############################2二级菜单-我的#############################*/
/**
  * @简介     系统设置二级菜单
  * @返回值   用户选择的菜单项
  */
static MYItem menu2_my(void) {
		uint32_t last_query_time = 0; // 记录上次查询时间
		Query_current_song();
    MYItem currentItem = MYBACK;
    uint8_t playState = 0; // 0:暂停 1:播放
		uint8_t refresh = 1;

    while(1) {
				if(HAL_GetTick() - last_query_time > 300) {
            Query_current_song();
            last_query_time = HAL_GetTick();
        }
				//绘制部分
				if(refresh){
					  OLED_Clear();
						// 顶部状态栏
						OLED_ShowString(8, 0, "<-", OLED_8X16);
						OLED_Printf(OLED_WIDTH/2-16 * 3/2, 0, OLED_8X16, "第%d首", current_song);
						OLED_ShowString(OLED_WIDTH-32, 0, "设置", OLED_8X16);

						// 播放控制区
						char* playText = playState ? "暂停" : "播放";
						OLED_ShowString(OLED_WIDTH/2-16, OLED_HEIGHT-16,playText, OLED_8X16);
						
						OLED_ShowString(0, OLED_HEIGHT-16, "上", OLED_8X16);
						OLED_ShowString(OLED_WIDTH-16, OLED_HEIGHT-16, "下", OLED_8X16);
				}
					
				//按键控制部分
        switch(Key_GetNum()) {
            case KEY_UP:
                currentItem = (currentItem == MYBACK) ? (MYItem)(MYITEM_TOTAL-1) : (MYItem)(currentItem-1);
								
                break;
                
            case KEY_DOWN:
                currentItem = (currentItem == (MYItem)(MYITEM_TOTAL-1)) ? MYBACK : (MYItem)(currentItem+1);
                break;
                
            case KEY_ENTER:
								if (currentItem == MYBACK) return MYBACK;
								if (currentItem == PLAY) {
										playState ^= 1;
										if (playState) {
												Play_MP3();    // DMA发送播放指令
												refresh =1;
										} else {
												Pause_MP3();   // DMA发送暂停指令
										}
								} 
								else if (currentItem == PRE) {
										Prev_MP3();        // DMA发送上一首
										Query_current_song();
									if(playState==0){
										playState =1;
									}
									refresh = 1;
								}
								else if (currentItem == NEXT) {
										Next_MP3();        // DMA发送下一首
										Query_current_song();
									if(playState==0){
										playState =1;
									}
									refresh = 1;
								}else if (currentItem == SETTING){
									//如果收到返回的值是枚举变量MYBACK的话，将refresh置为1，重绘当前菜单//
										if(MY_SETTING() == MYBACK){
												refresh = 1;
										}
								}
								break;
        }

        // 反色显示当前选中项
        switch(currentItem) {
            case MYBACK:
                OLED_ReverseArea(8, 0, 16, 16); // 返回箭头
                break;
            case SETTING:
                OLED_ReverseArea(OLED_WIDTH-32, 0, 32, 16); // 设置按钮
                break;
            case PRE:
                OLED_ReverseArea(0, OLED_HEIGHT-16, 16, 16); // 上键
                break;
            case PLAY:
                OLED_ReverseArea(OLED_WIDTH/2-16, OLED_HEIGHT-16, 32 , 16); // 播放/暂停
                break;
            case NEXT:
                OLED_ReverseArea(OLED_WIDTH-16, OLED_HEIGHT-16, 16, 16); // 下键
                break;
            default: break;
        }
				OLED_Update();
    }
}

/*====================== 三级菜单：2.1我的>设置>音量/播放模式 ======================*/
static MY_SET_ITEM MY_SETTING(){
		Query_Volume();//发送查询音量命令
		MY_SET_ITEM currentItem = MYSET_BACK;
		uint8_t refresh = 1;
	
		while(1){
			if(refresh) {
            OLED_Clear();
            // 三级菜单布局
						OLED_ShowString(8, 0,(currentItem == MYSET_BACK)      ? "<-" : " ", OLED_8X16);
            OLED_ShowString(8, 16,  (currentItem == VOLUME) ? "> 音量" : "  音量", OLED_8X16);
            OLED_ShowString(8, 34, (currentItem == PLAY_MODE)       ? "> 播放模式" : "  播放模式", OLED_8X16);
            OLED_Update();
            refresh = 0;
        }
			
				switch(Key_GetNum()) {
            case KEY_UP:    // 上移
                currentItem = (currentItem == MYSET_BACK) ? PLAY_MODE : (MY_SET_ITEM)(currentItem - 1);
                refresh = 1;
                break;
                
            case KEY_DOWN:  // 下移
                currentItem = (currentItem == PLAY_MODE) ? MYSET_BACK : (MY_SET_ITEM)(currentItem + 1);
                refresh = 1;
                break;
                
            case KEY_ENTER: // 确认
                if(currentItem == MYSET_BACK) {
									return MYSET_BACK;//返回MYSET_BACK这个枚举值给上一级,上一级的函数判断后，将refresh置为1，重新刷新它那级的菜单s
                } else {
                    /* 通过回调执行实际功能 */
                    switch(currentItem) {
                        case VOLUME:
                            VOL_SET();
                            break;
												case PLAY_MODE:
                            PLAYMODE();
                            break;
                        default: break;
                    }
                    refresh = 1; // 操作后刷新界面
                }
                break;
        }
        HAL_Delay(80);
		}
}
/*====================== 四级菜单：2.1.1我的>设置>音量>音量设置 ======================*/
static uint8_t VOL_SET() {
    uint8_t volumeLevel = Query_Volume();//发送查询音量命令
    uint8_t refresh = 1;
    uint8_t currentItem = 0;  // 0是<-;1是音量调节
    int inVolumeMode = 0;   // 是否在音量调整模式/0否，1是
    uint8_t barX = 56, barY = 28, barWidth = 70, barHeight = 16;
    
    // 定义音量范围
    const uint8_t VOLUME_MIN = 0;
    const uint8_t VOLUME_MAX = 30;

    while(1) {
        if(refresh) {
            OLED_Clear();
            OLED_ShowString(8, 0, (currentItem == 0) ? "<-" : " ", OLED_8X16);
						char volStr[16];
						sprintf(volStr, "音量:%d", volumeLevel);
						OLED_ShowString(0, 28, volStr, OLED_8X16);
            OLED_DrawRectangle(barX, barY, barWidth, barHeight, OLED_UNFILLED);
            
            // 确保音量在有效范围内
            volumeLevel = (volumeLevel > VOLUME_MAX) ? VOLUME_MAX : volumeLevel;
            
            uint8_t fillWidth = ((int)volumeLevel * barWidth) / VOLUME_MAX;
            if(fillWidth > 0) {
                OLED_DrawRectangle(barX, barY, fillWidth, barHeight, OLED_FILLED);
            }
            if (currentItem == 1) {
                if (inVolumeMode == 1) {
                    OLED_ShowString(OLED_WIDTH-16, 12, "*", OLED_8X16);
                }//在音量调节模式下才显示*
                OLED_ReverseArea(0, 28, 32, 16);
            }
            OLED_Update();
            refresh = 0;
        }
        
        switch(Key_GetNum()) {
            case KEY_UP:
                if (inVolumeMode) {    // 如果在音量调整模式
                    if(volumeLevel < VOLUME_MAX) {
												Volume_Add();
                        volumeLevel++; // 增加音量图标
                    }
                    // 发送音量增加指令
                    refresh = 1;
                } else {               // 如果在主菜单
                    currentItem = (currentItem == 0) ? 1 : 0; // 切换选项
                    refresh = 1;
                }
                break;

            case KEY_DOWN:
                if (inVolumeMode) {    // 如果在音量调整模式
                    if(volumeLevel > VOLUME_MIN) {
												Volume_Sub();
                        volumeLevel--; // 减少音量
                    }
                    // 发送音量减少指令
                    refresh = 1;
                } else {               // 如果在主菜单
                    currentItem = (currentItem == 0) ? 1 : 0; // 切换选项
                    refresh = 1;
                }
                break;

            case KEY_ENTER:
                if (inVolumeMode) {    // 如果在音量调整模式
                    inVolumeMode = 0;  // 退出到主菜单
                    refresh = 1;
                } else {               // 如果在主菜单
                    if (currentItem == 0) {
                        return MYSET_BACK;  // 返回上一级菜单
                    } else if (currentItem == 1) {
                        inVolumeMode = 1;   // 进入音量调整模式
                        refresh = 1;
                    }
                }
                break;
        }
        HAL_Delay(80);
    }
}

/*====================== 四级菜单：2.1.2 我的>设置>播放模式>播放模式设置 ======================*/
uint8_t play_flag =0;
static PLAY_MODE_ITEM PLAYMODE(){
	static uint8_t refresh = 1;
	PLAY_MODE_ITEM currentItem =	PALY_MODE_BACK;
	uint8_t play_flag =0;
	
   while(1){
		 if(refresh){
		  OLED_Clear();
            // 三级菜单布局
						if(play_flag ==0){
							OLED_ShowString(OLED_WIDTH-16, 16, "*", OLED_8X16);
						}else if(play_flag ==1){
							OLED_ShowString(OLED_WIDTH-16, 34, "*", OLED_8X16);
						}else if(play_flag ==2){
							OLED_ShowString(OLED_WIDTH-16, 50, "*", OLED_8X16);
						}
						OLED_ShowString(8, 0,(currentItem == PALY_MODE_BACK)      ? "<-" : " ", OLED_8X16);
            OLED_ShowString(8, 16,  (currentItem == Loop)? "> 循环播放" : "  循环播放", OLED_8X16);
						OLED_ShowString(8, 34, (currentItem == Repeat)? "> 重复播放" : "  重复播放", OLED_8X16);
						OLED_ShowString(8, 50, (currentItem == Random)? "> 随机播放" : "  随机播放", OLED_8X16);
            OLED_Update();
            refresh = 0;
			OLED_Update();
		 }
	 switch(Key_GetNum()) {
            case KEY_UP:    // 上移
                currentItem = (currentItem == PALY_MODE_BACK) ? Random : (PLAY_MODE_ITEM)(currentItem - 1);
                refresh = 1;
                break;
                
            case KEY_DOWN:  // 下移
                currentItem = (currentItem == Random) ? PALY_MODE_BACK : (PLAY_MODE_ITEM)(currentItem + 1);
                refresh = 1;
                break;
                
            case KEY_ENTER: // 确认
                if(currentItem == PALY_MODE_BACK) {
									return PALY_MODE_BACK;		//返回PALY_MODE_BACK这个枚举值给上一级,上一级的函数判断后，将refresh置为1，重新刷新它那级的菜单s
                } else {
                    /* 通过回调执行实际功能 */
                    switch(currentItem) {
                        case Loop:
														Mp3_LoopPlay();
														play_flag =0;
                            break;
												case Repeat:
														Mp3_RepeatPlay();
														play_flag =1;
                            break;
												case Random:
														Mp3_RandomPlay();
														play_flag =2;
                            break;
                        default: break;
                    }
                    refresh = 1; // 操作后刷新界面
                }
                break;
        }
	 }
}

/*====================== 回调函数示例实现 ======================*/
// 亮度调节实际功能（可放在硬件驱动层）
void HandleBrightnessAdjust(void) {
    OLED_Clear();
    OLED_ShowString(16, 24, "亮度75%", OLED_8X16);
    OLED_Update();
    // 这里添加实际PWM控制代码
    HAL_Delay(1000);
}

// 显示模式切换实际功能
void HandleDisplayModeChange(void) {
    OLED_Clear();
    OLED_ShowString(16, 24, "显示模式1", OLED_8X16);
    OLED_Update();
    // 这里添加实际显示模式切换代码
    HAL_Delay(1000);
}
